package com.cans;

import org.junit.Test;

/**
 * demo
 *
 * @author cans
 * @date 2022/5/14
 **/
public class ExpressionDemo {

    @Test
    public void demoTest() {

        String ex = "a+b-c";

        Context context = new Context();
        context.put("a", 1);
        context.put("b", 9);
        context.put("c", 3);
        Expression expression = this.parse(ex.toCharArray());
        int interpret = expression.interpret(context);
        System.out.println(ex + " = " + interpret);

    }

    private Expression parse(char[] arr) {
        String one = String.valueOf(arr[0]);
        ValueExpression left = new ValueExpression(one);
        if (arr.length == 1) {
            return left;
        }
        String op = String.valueOf(arr[1]);
        Expression nextExp = this.parse(getNextChar(arr));
        if (op.equals("+")) {
            return new AddExpression(left, nextExp);
        } else if (op.equals("-")) {
            return new SubExpression(left, nextExp);
        }
        return null;
    }


    private char[] getNextChar(char[] arr) {
        char[] newArr = new char[arr.length - 2];
        System.arraycopy(arr, 2, newArr, 0, arr.length - 2);
        return newArr;
    }
}
